<?php
/**
 * Created by PhpStorm.
 * User: 64423
 * Date: 2018/10/31
 * Time: 10:58
 */

namespace app\api\home;


use app\cms\model\MoneyModel;
use app\shop\model\GoodsModel;
use app\shop\model\OrderGoodsModel;
use app\shop\model\OrderModel;
use app\shop\model\SpecPriceModel;
use app\shop\model\UserModel;
use think\Db;

/** 订单操作
 * Class Collect
 * @package app\api\home
 */
class Order extends Common
{
    // 生成订单
    public function submit()
    {
        $data = input('post.',[]);
        $user_id = $data['user_id'];
        if($user_id == 0){
            return _json(401, '请先登录',[]);
        }

        $goods_list = $data['goodsList'];
        $goods_total_price = $data['goodsTotalPrice'];  //商品总价
        $actual_price = $data['actualPrice'];   //实际需要支付的总价
        $freight_price = $data['freightPrice']; //邮费
        $_total = 0;
        $goods_count = 0;
        $goods = [];
        $is_cart = $data['isCart'];
        $cartIds = [];
        foreach ($goods_list as $k=>$v){
            $info = GoodsModel::getOne($v['goods_id']);
            // 商品下架
            if($info['is_sell'] == 0){
                return _json(400, '执行成功',['msg'=>'商品已下架']);
                break;
            }
            if($is_cart){
                array_push($cartIds, $v['cart_id']);
            }
            // 统计价格
            if($info['type_id'] == 0){
                $_total += $info['shop_price'] * $v['goods_num'];
                $price = $info['shop_price'];
                $spec_info['key_name'] = '';
            }else{
                // 查询规格价格
                $spec_info = SpecPriceModel::getByKey($v['goods_id'], $v['key']);
                $_total += $spec_info['price'] * $v['goods_num'];
                $price = $spec_info['price'];
            }

            $goods[$k]['goods_id']          =  $v['goods_id'];
            $goods[$k]['goods_thumb']       =  $info['thumb_url'];
            $goods[$k]['goods_name']        =  $info['goods_name'];
            $goods[$k]['goods_num']         =  $v['goods_num'];
            $goods[$k]['goods_price']       =  $price;
            $goods[$k]['goods_total']       =  $price * $v['goods_num'];
            $goods[$k]['spec_key']          =  $v['key'];
            $goods[$k]['spec_key_name']     =  $spec_info['key_name'];

            $goods_count += $v['goods_num'];
        }
        if($_total != $goods_total_price){
            return _json(400, '执行成功',['msg'=>'商品价格错误']);
        }

        //生成订单
        $address = Db::name('address')->where('id',$data['addressId'])->find();
        $order_amount = $goods_total_price + $freight_price;
        $data = [
            'order_sn' => makeOrderSn(),
            'user_id' => $user_id,
            'user_name' => $address['user_name'],   // 收货人
            'tel_number' => $address['tel_number'],
            'address' => $address['province_name'].$address['city_name'].$address['county_name'].$address['detail_info'],
            'goods_count' => $goods_count,
            'goods_total' => $goods_total_price,
            'freight_price' => $freight_price,
            'order_amount' => $order_amount,
            'add_time' => time()
        ];
        $order = OrderModel::create($data);
        foreach ($goods as $k=>$v){
            $goods[$k]['order_id'] = $order->order_id;
        }
        $user_money = Db::name('user')->where('user_id',$user_id)->value('user_money');
        $data = [
            'order_id' => $order->order_id,
            'user_money' => $user_money
        ];
        if($order){
            if($is_cart){
                $cartIds = implode(',', $cartIds);
                Db::name('cart')->whereIn('id',$cartIds)->delete();
            }
            OrderGoodsModel::insertAll($goods);
            return _json(0, '执行成功', $data);
        }else{
            return _json(400, '执行成功',['msg'=>'生成订单失败']);
        }
    }

    /**
     * 确认余额支付
     */
    public function confirmPay()
    {
        $order_id = input('get.orderId',0);
        $info = Db::name('order')->where('order_id',$order_id)->find();
        if($info['pay_status'] == 1){
            return _json(400, '执行成功',['msg'=>'订单已支付']);
        }
        $user_info = UserModel::getOne($info['user_id']);
        if($user_info['user_money'] < $info['order_amount']){
            return _json(400, '执行成功',['msg'=>'余额不足']);
        }
        // 变更余额
        UserModel::updateMoney($info['user_id'], 2, $info['order_amount'], '下单支付');
        // 变更订单状态
        $data = [
            'pay_status' => 1,
            'order_status' => 1,
            'pay_time' => time(),
            'pay_name' => '余额支付'
        ];
        $res = OrderModel::updateStatus($order_id, $data);
        if($res){
            return _json(0, '执行成功',['msg'=>'支付成功']);
        }else{
            return _json(400, '执行成功',['msg'=>'支付失败']);
        }

    }

    // 订单列表
    public function lists()
    {
        $page = input('get.page',1);
        $size = input('get.size',10);
        $user_id = input('get.user_id',0);
        $order_status = input('get.order_status',-1);
        if($order_status == -1){
            $where = '';
        }else{
            $where = ['order_status'=>$order_status];
        }
        $list = Db::name('order')->where($where)->where('user_id',$user_id)
            ->order('order_id desc')->page($page, $size)->select();
        if(!$list){
            return _json(300, '执行成功',['msg'=>'无数据']);
        }
        foreach ($list as $k=>$v){
            $goods = Db::name('order_goods')->where('order_id', $v['order_id'])->order('id')->select();
            foreach ($goods as $k2=>$v2){
                $goods[$k2]['goods_thumb'] = 'http://'.$host = $_SERVER['HTTP_HOST'] . get_file_path($v2['goods_thumb']);
            }
            $list[$k]['goods'] = $goods;
        }
        $data = [
            'data' => $list
        ];
        return _json(0, '执行成功',$data);
    }

    // 订单详情
    public function detail()
    {
        $order_id = input('get.orderId',0);

        $info = Db::name('order')->where('order_id',$order_id)->find();
        $info['goods'] = Db::name('order_goods')->where('order_id',$order_id)->order('id')->select();
        foreach ($info['goods'] as $k=>$v){
            $info['goods'][$k]['goods_thumb'] = 'http://'.$host = $_SERVER['HTTP_HOST'] . get_file_path($v['goods_thumb']);
        }
        $info['add_time'] = date('Y-m-d H:i:s', $info['add_time']);
        return _json(0, '执行成功',['detail'=>$info ]);
    }

    // 确认收货
    public function confirmOrder()
    {
        $order_id = input('get.orderId',0);
        $info = Db::name('order')->where('order_id',$order_id)->find();
        if($info['pay_status'] == 0){
            return _json(400, '执行成功',['msg'=>'订单未支付']);
        }
        if($info['shipping_status'] == 1){
            return _json(400, '执行成功',['msg'=>'已确认收货']);
        }
        $data = [
            'shipping_status' => 1,
            'order_status' => 3,
            'confirm_time' => time()
        ];
        $res = Db::name('order')->where('order_id',$order_id)->update($data);
        if($res){
            return _json(0, '执行成功',['msg'=>'确认收货成功']);
        }else{
            return _json(400, '执行成功',['msg'=>'错误']);
        }
    }

    // 取消订单 删除
    public function cancelOrder()
    {
        $order_id = input('get.orderId',0);
        $res = OrderModel::destroy($order_id);
        if($res){
            return _json(0, '执行成功',['msg'=>'取消成功']);
        }else{
            return _json(400, '执行成功',['msg'=>'取消失败']);
        }
    }
}